package com.dgut.service;

import com.dgut.pojo.ImportantArea;
import com.dgut.util.RedisUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.boot.json.JacksonJsonParser;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
public class CityRiskrankService {
    /*
     * 接口调用
     */
    private RestTemplate restTemplateHttps = new RestTemplate();

    //调用Redis工具类
    final
    RedisUtils redisUtils;

    public CityRiskrankService(RedisUtils redisUtils) {
        this.redisUtils = redisUtils;
    }

    /*
     * SHA-256 加密
     * 国务院疫情风险接口
     * http://103.66.32.242:8005/zwfwMovePortal/interface/interfaceJson
     * http://bmfw.www.gov.cn/yqfxdjcx/risk.html
     *
     * @param str 被加密的字符串
     * @return
     */
    public static String getSHA256StrJava(String str) {
        MessageDigest messageDigest;
        String encodeStr = "";
        try {
            messageDigest = MessageDigest.getInstance("SHA-256");
            messageDigest.update(str.getBytes(StandardCharsets.UTF_8));
            byte[] bytes = messageDigest.digest();
            StringBuffer stringBuffer = new StringBuffer();
            String temp = null;
            for (int i = 0; i < bytes.length; i++) {
                temp = Integer.toHexString(bytes[i] & 0xFF);
                if (temp.length() == 1) {
                    //1得到一位的进行补0操作
                    stringBuffer.append("0");
                }
                stringBuffer.append(temp);
            }
            encodeStr = stringBuffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return encodeStr;
    }


    //从页面获取的数据封成map
    public Map<String, Object> test() {
        //获取时间戳
        long timestamp = LocalDateTime.now().toEpochSecond(ZoneOffset.of("+8"));
        String url = "http://103.66.32.242:8005/zwfwMovePortal/interface/interfaceJson";
        //以下常量值都是从网页源代码上获取到的------start
        final String STATE_COUNCIL_SIGNATURE_KEY = "fTN2pfuisxTavbTuYVSsNJHetwq5bJvCQkjjtiLM2dCratiA";
        final String STATE_COUNCIL_X_WIF_NONCE = "QkjjtiLM2dCratiA";
        final String STATE_COUNCIL_X_WIF_PAASID = "smt-application";
        //国务院疫情防控查询 appId
        final String STATE_COUNCIL_APP_ID = "NcApplication";
        //国务院疫情防控查询 PASSID
        final String STATE_COUNCIL_PASSID = "zdww";
        //国务院疫情防控查询 秘钥
        final String STATE_COUNCIL_NONCE = "123456789abcdefg";
        //国务院疫情防控查询 token
        final String STATE_COUNCIL_TOEKN = "23y0ufFl5YxIyGrI8hWRUZmKkvtSjLQA";
        //国务院疫情防控查询 key
        final String STATE_COUNCIL_KEY = "3C502C97ABDA40D0A60FBEE50FAAD1DA";
        //以下常量值都是从网页源代码上获取到的------end
        HttpHeaders requestHeaders = new HttpHeaders();
        Map<String, Object> body = new HashMap<>(10);
        //计算签名要用的字符串
        String signatureStr = String.format("%d%s%d", timestamp, STATE_COUNCIL_SIGNATURE_KEY, timestamp);
        //计算签名
        String signature = getSHA256StrJava(signatureStr).toUpperCase();
        //请求头参数封装
        requestHeaders.add("x-wif-nonce", STATE_COUNCIL_X_WIF_NONCE);
        requestHeaders.add("x-wif-paasid", STATE_COUNCIL_X_WIF_PAASID);
        requestHeaders.add("x-wif-signature", signature);
        requestHeaders.add("x-wif-timestamp", String.valueOf(timestamp));
        //body参数封装
        body.put("appId", STATE_COUNCIL_APP_ID);
        body.put("paasHeader", STATE_COUNCIL_PASSID);
        body.put("timestampHeader", timestamp);
        body.put("nonceHeader", STATE_COUNCIL_NONCE);
        //请求参数
        signatureStr = String.format("%d%s%s%d", timestamp, STATE_COUNCIL_TOEKN, STATE_COUNCIL_NONCE, timestamp);
        String signatureHeader = getSHA256StrJava(signatureStr).toUpperCase();
        body.put("signatureHeader", signatureHeader);
        body.put("key", STATE_COUNCIL_KEY);
        HttpEntity<String> httpEntity = new HttpEntity(body, requestHeaders);
        ResponseEntity<String> response = restTemplateHttps.exchange(url, HttpMethod.POST, httpEntity, String.class);
        JacksonJsonParser jacksonJsonParser = new JacksonJsonParser();
        Map<String, Object> resultMap = jacksonJsonParser.parseMap(response.getBody());
        return resultMap;
    }

    /*
    *将map格式解析为string类型
    */
    public String getImportantArea() throws InvocationTargetException, IllegalAccessException {
        JacksonJsonParser jacksonJsonParser = new JacksonJsonParser();
        Map<String, Object> data = (LinkedHashMap<String, Object>) test().get("data");
        String important = "高风险地区：\n";
        List highlist = (List)data.get("highlist");
        List middlelist = (List) data.get("middlelist");
        for (int j = 0; j < highlist.size(); j ++){
            ImportantArea heightArea = new ImportantArea();
            BeanUtils.populate(heightArea,(Map<String, ? extends Object>) highlist.get(j));
            important = important + (j+1) + '.' + heightArea.getArea_name() + ":";
            List<String> heightCommunitys = heightArea.getCommunitys();
            int heightSize = heightCommunitys.size();
            for (int i = 0; i < heightSize; i++) {
                if (i != heightSize - 1){
                    important = important +heightCommunitys.get(i)+",";
                }else {
                    important = important +heightCommunitys.get(i)+"\n";
                }
            }
        }
        important = important + "中风险地区：\n";
        for (int j = 0;j < middlelist.size();j++) {
            ImportantArea area = new ImportantArea();
            BeanUtils.populate(area, (Map<String, ? extends Object>) middlelist.get(j));
            important = important + (j+1) + '.' +area.getArea_name() + ":";
            List<String> communitys = area.getCommunitys();
            for (int i = 0; i < communitys.size(); i++) {
                if (i != communitys.size() - 1) {
                    important = important + communitys.get(i) + ",";
                }else {
                    important = important + communitys.get(i) + "\n";
                }
            }
        }
        return important;
    }


    //定时获取疫情中高风险地区信息，存放在Redis中
    @Scheduled(cron = "0 50 23 * * ?")
    @PostConstruct
    public void setImportantArea() throws InvocationTargetException, IllegalAccessException {
        String importantArea = getImportantArea();
        redisUtils.getAndSet("important_area",importantArea);
    }

    //从Redis获取中高风险地区信息
    public String getImportantAreaFromRedis(){
        return redisUtils.get("important_area");
    }

}
